package cn.tristenstudy.blog.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @author xichen1.li
 * @date 2020-10-28 20:18
 */
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * 配置druid数据监控,后台监控
     *
     * @return bean
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //后台需要有人登陆：账号密码配置
        HashMap<String, String> initParameters = new HashMap<>(2);

        //增加配置，登陆的key是固定的
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "admin");

        //允许谁可以访问,空则所有人可以访问
        initParameters.put("allow", "");

        //禁止谁访问
        initParameters.put("haha", "192.168.11.123");

        //设置初始化参数
        bean.setInitParameters(initParameters);
        return bean;
    }

    /**
     * 配置web过滤器
     *
     * @return baen
     */
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();

        bean.setFilter(new WebStatFilter());

        //过滤请求
        HashMap<String, String> initParameters = new HashMap<>();
        //设置过滤哪些请求不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/**");

        bean.setInitParameters(initParameters);
        return bean;
    }

}
